package com.example.blogdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blogdemo.common.Utils.BlogBeanUtils;
import com.example.blogdemo.common.Utils.JwtUtils;
import com.example.blogdemo.common.Utils.SecurityUtils;
import com.example.blogdemo.common.exception.BlogException;
import com.example.blogdemo.mapper.BlogMapper;
import com.example.blogdemo.mapper.UserMapper;
import com.example.blogdemo.pojo.dataobject.BlogInfo;
import com.example.blogdemo.pojo.dataobject.UserInfo;
import com.example.blogdemo.pojo.request.UserRequest;
import com.example.blogdemo.pojo.respond.GetUserInfo;
import com.example.blogdemo.pojo.respond.UserRespond;
import com.example.blogdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlogMapper blogMapper;


    @Override
    public UserRespond login(UserRequest userRequest) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag, 0).eq(UserInfo::getUserName, userRequest.getUserName());

        UserInfo userInfo = userMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            throw new BlogException("用户不存在");
        }
//        if (!userInfo.getPassword().equals(userRequest.getPassword()) ) {
//            throw new BlogException("密码错误");
//        }

        if (!SecurityUtils.checkPassword(userRequest.getPassword(), userInfo.getPassword())) {
            throw new BlogException("密码错误");
        }


        UserRespond userRespond = new UserRespond();
        userRespond.setUserId(userInfo.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("name", userInfo.getUserName());
        String jwt = JwtUtils.getJwt(map);
        userRespond.setToken(jwt);
        return userRespond;




    }

    @Override
    public GetUserInfo getUserInfo(Integer userId) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag, 0).eq(UserInfo::getId, userId);
        UserInfo userInfo = userMapper.selectOne(queryWrapper);
        return BlogBeanUtils.transUser(userInfo);

    }

    @Override
    public GetUserInfo getAuthorInof(Integer blogId) {


        try {
            BlogInfo blogInfo = blogMapper.selectById(blogId);
            return getUserInfo(blogInfo.getUserId());
        }catch (Exception e) {
            log.error("获取作者信息失败, e:{}", e);
            throw new BlogException("获取作者信息失败");
        }


    }
}
